// Copyright 2019 The rhyme_lph Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Q [author] rhyme_lph
// g [email]  rhymelph@gmail.com
// V [github] https://github.com/rhymelph

import 'package:base_plugin/base_plugin.dart';
import 'package:finance_app/generated/l10n.dart';
import 'package:finance_app/src/common/app_colors.dart';
import 'package:finance_app/src/common/app_spaces.dart';
import 'package:finance_app/src/entities/employee_contact_entity.dart';
import 'package:finance_app/src/entities/payslips_item_entity.dart';
import 'package:finance_app/src/provider/hr_payroll/payroll/payroll_detail_provider.dart';
import 'package:finance_app/src/router_gen/router_meta.dart';
import 'package:finance_app/src/utils/date_time_utils.dart';
import 'package:finance_app/src/utils/form_utils.dart';
import 'package:finance_app/src/widgets/button/normal_border_button.dart';
import 'package:finance_app/src/widgets/button/normal_popup_button.dart';
import 'package:finance_app/src/widgets/button/normal_text_button.dart';
import 'package:finance_app/src/widgets/common_app_bar.dart';
import 'package:finance_app/src/widgets/form/add_form.dart';
import 'package:finance_app/src/widgets/form/between_item_form.dart';
import 'package:finance_app/src/widgets/form/form_edit_status_inherited_widget.dart';
import 'package:finance_app/src/widgets/form/status_line_form.dart';
import 'package:finance_app/src/widgets/form/value_select_form.dart';
import 'package:finance_app/src/widgets/list_item/list_header_item.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:tuple/tuple.dart';

export 'package:finance_app/src/entities/payslips_item_entity.dart';

@RouterMeta(paramName: "payrollDetailPage")
class PayrollDetailPage extends StatefulWidget {
  final PayslipsItemEntity data;

  const PayrollDetailPage({Key key, this.data}) : super(key: key);

  @override
  _PayrollDetailPageState createState() => _PayrollDetailPageState();
}

class _PayrollDetailPageState extends State<PayrollDetailPage>
    with PagePresenter<PayrollDetailPage, PayrollDetailProvider> {
  String get title => provider.id == null
      ? S.current.new_payslip_details
      : provider.isEdit == true
          ? S.current.edit_payslip_details
          : S.current.payslip_details;

  Widget get rightButton => listBuilder<bool>(
        selector: (_, __) => __.isEdit,
        builder: (BuildContext context, bool value, Widget child) =>
            provider.id != null && provider.isEdit == false
                ? _buildPopButton()
                : _buildSaveBtn(),
      );

  @override
  PreferredSizeWidget get appBar => getDefaultAppBar(
      titleWidget: listBuilder<bool>(
        selector: (_, __) => __.isEdit,
        builder: (BuildContext context, bool value, Widget child) =>
            Text(title),
      ),
      actions: [rightButton]);

  Widget _buildPopButton() => listBuilder<Tuple2<bool, int>>(
        selector: (_, __) => Tuple2(__.isEdit, __.menuList.length),
        builder:
            (BuildContext context, Tuple2<bool, int> value, Widget child) =>
                value.item1 == true || value.item2 == 0
                    ? Container()
                    : NormalMorePopupButton(
                        onSelect: provider.onSelectMenu,
                        menuList: provider.menuList,
                      ),
      );

  Widget _buildSaveBtn() {
    return listBuilder<bool>(
      selector: (_, __) => pageStatus != PageStatus.loading,
      builder: (BuildContext context, bool value, Widget child) => value == true
          ? NormalSaveTextButton(
              onTap: provider.onSave,
            )
          : Container(),
    );
  }

  @override
  void initState() {
    provider.initData(widget.data);

    super.initState();
  }

  @override
  Widget wrapperBody(Widget child) {
    return listBuilder<bool>(
        selector: (_, __) => __.isEdit == true || provider.id == null,
        builder: (BuildContext context, bool value, Widget child) =>
            FormEditStatusInheritedWidget(
              isEdit: value,
              child: child,
            ),
        child: child);
  }

  @override
  Widget get buildWidget => ColoredBox(
        color: Colors.white,
        child: ListView(
          children: [
            listBuilder<String>(
              selector: (_, __) => __.statusType,
              builder: (BuildContext context, String value, Widget child) =>
                  StatusLineForm(
                status: value,
                model: ReimburseModel.payslip,
              ),
            ),
            listBuilder<String>(
              selector: (_, __) => __.payslips?.number,
              builder: (BuildContext context, String value, Widget child) =>
                  ValueSelectForm(
                title: S.current.payslip_number,
                value: value,
              ),
            ),
            listBuilder<String>(
              selector: (_, __) => __.payslips?.name,
              builder: (BuildContext context, String value, Widget child) =>
                  ValueSelectForm(
                title: S.current.employee_name,
                value: value,
              ),
            ),
            ValueSelectForm(
              title: S.current.salary_period,
              value:
                  '${DateTimeUtils.formatDateTimeString(provider.data.startDate)} - ${DateTimeUtils.formatDateTimeString(provider.data.endDate)}',
            ),
            ValueSelectForm(
              title: S.current.total_working_days,
              value: '${provider.data.actualDays}',
              border: null,
            ),
            ListHeaderItem(
              title: S.current.income,
            ),
            listBuilder<List<EmployeeContactIncomeData>>(
              selector: (_, __) => List.from(__.incomeData),
              builder: (BuildContext context,
                      List<EmployeeContactIncomeData> value, Widget child) =>
                  Column(
                children: List.generate(value.length, (index) {
                  final e = provider.incomeData[index];
                  return BetweenItemForm(
                    left: e.name,
                    right: '${e.currencyCode} ${e.amount.toStringAsFixed(2)}',
                    hasBottomBorder:
                        (value.length != index + 1) || (provider.isEdit),
                    onTap: () {
                      if (provider.isEdit == true) {
                        provider.onIncomeTypeDetail(e, index == 0);
                      }
                    },
                  );
                }),
              ),
            ),
            AddForm(
              title: S.current.add_income_type,
              onTap: provider.onAddIncomeType,
            ),
            ListHeaderItem(
              title: S.current.deduction,
            ),
            BetweenItemForm(
              left: S.current.employee_cpf,
              right:
                  '(${provider.data?.incomeData?.first?.currencyCode} ${provider.data.employeeCpf.toStringAsFixed(2)})',
              isDisable: true,
            ),
            listBuilder<Tuple2<String, String>>(
              selector: (_, __) =>
                  Tuple2(__.contribution?.name, __.contributionAmount),
              builder: (BuildContext context, Tuple2<String, String> value,
                      Widget child) =>
                  BetweenItemForm(
                left: value.item1 == 'Opted Out'
                    ? S.current.shg_contribution
                    : value.item1,
                onTap: provider.onSelectContribution,
                right: value.item1 == 'Opted Out'
                    ? value.item1
                    : '(${provider.data.incomeData.first.currencyCode} ${value.item2})',
                hasBottomBorder: provider.isEdit,
              ),
            ),
            listBuilder<List<EmployeeContactDeductionData>>(
              selector: (_, __) => List.from(__.deductionData),
              builder: (BuildContext context,
                      List<EmployeeContactDeductionData> value, Widget child) =>
                  Column(
                children: List.generate(value.length, (index) {
                  final e = provider.deductionData[index];
                  return BetweenItemForm(
                    left: e.name,
                    onTap: () => provider.onSelectFixedDeduction(e),
                    right: '(${e.currencyCode} ${e.amount})',
                    hasBottomBorder:
                        (value.length != index + 1) || (provider.isEdit),
                  );
                }),
              ),
            ),
            AddForm(
              title: S.current.add_deduction,
              onTap: provider.onAddFixedDeduction,
            ),
            ListHeaderItem(
              title: S.current.summary,
            ),
            listBuilder<String>(
              selector: (_, __) => __.payslips?.total?.toStringAsFixed(2),
              builder: (BuildContext context, String value, Widget child) =>
                  BetweenItemForm(
                left: S.current.gross_wages,
                right: '${provider.data.incomeData.first.currencyCode} $value',
                isDisable: true,
                hasBottomBorder: false,
              ),
            ),
            FormStatusWidget(
              enable: Container(),
              disable: listBuilder<Tuple3<num, num, bool>>(
                selector: (_, __) => Tuple3<num, num, bool>(
                    __.payslips?.nettAmount,
                    __.payslips?.reimbursement,
                    __.statusType == 'closed'),
                builder: (BuildContext context, Tuple3<num, num, bool> value,
                        Widget child) =>
                    BetweenItemForm(
                  left: S.current.nett_wages,
                  right:
                      '${provider.data.incomeData.first.currencyCode} ${value.item1.toStringAsFixed(2)}',
                  textColor:
                      value.item2 == 0 && value.item3 ? aceGreenColor : null,
                  hasBottomBorder: false,
                ),
              ),
            ),
            FormStatusWidget(
              enable: Container(),
              disable: listBuilder<Tuple2<num, bool>>(
                selector: (_, __) => Tuple2<num, bool>(
                    __.payslips?.reimbursement, __.statusType == 'closed'),
                builder: (BuildContext context, Tuple2<num, bool> value,
                        Widget child) =>
                    Visibility(
                  visible: value.item1 != 0,
                  child: Column(
                    children: [
                      BetweenItemForm(
                        left: S.current.reimbursement,
                        right:
                            '${provider.data.incomeData.first.currencyCode} ${value.item1?.toStringAsFixed(2)}',
                        hasBottomBorder: false,
                      ),
                      BetweenItemForm(
                        left: S.current.total_paid,
                        right:
                            '${provider.data.incomeData.first.currencyCode} ${(value.item1 + provider.payslips.nettAmount)?.toStringAsFixed(2)}',
                        textColor: value.item2 ? aceGreenColor : null,
                        hasBottomBorder: false,
                      ),
                    ],
                  ),
                ),
              ),
            ),
            listBuilder<bool>(
              selector: (_, __) => __.statusType == 'closed',
              builder: (BuildContext context, bool value, Widget child) =>
                  value == true
                      ? Column(
                          children: [
                            FormStatusWidget(
                              enable: Container(),
                              disable: listBuilder<String>(
                                selector: (_, __) => __.paymentTypeName,
                                builder: (BuildContext context, String value,
                                        Widget child) =>
                                    BetweenItemForm(
                                  left: S.current.payment_method,
                                  right: value,
                                  hasBottomBorder: false,
                                  textColor: aceGreenColor,
                                ),
                              ),
                            ),
                            FormStatusWidget(
                              enable: Container(),
                              disable: listBuilder<DateTime>(
                                selector: (_, __) => __.paidAt,
                                builder: (BuildContext context, DateTime value,
                                        Widget child) =>
                                    BetweenItemForm(
                                  left: S.current.payment_date,
                                  right:
                                      '${DateTimeUtils.formatGlobalDateTime(value)}',
                                  hasBottomBorder: false,
                                  textColor: aceGreenColor,
                                ),
                              ),
                            ),
                            if (provider.data.bankAccountNumber != null)
                              FormStatusWidget(
                                enable: Container(),
                                disable: BetweenItemForm(
                                  left: S.current.bank_account,
                                  right: (provider.data.bankName ?? '') +
                                      ' ${provider.data.bankAccountNumber}',
                                  hasBottomBorder: false,
                                  textColor: aceGreenColor,
                                ),
                              ),
                          ],
                        )
                      : Container(),
            ),
            ListHeaderItem(
              title: S.current.company_contribution,
            ),
            FormStatusWidget(
              enable: Container(),
              disable: listBuilder<String>(
                selector: (_, __) =>
                    __.payslips?.employerCpf?.toStringAsFixed(2),
                builder: (BuildContext context, String value, Widget child) =>
                    BetweenItemForm(
                  left: S.current.employer_cpf,
                  right:
                      '${provider.data.incomeData.first.currencyCode} $value',
                  hasBottomBorder: false,
                ),
              ),
            ),
            AppSpaces.h40,
            listBuilder<List<String>>(
              selector: (_, __) => List.from(__.menuList),
              builder:
                  (BuildContext context, List<String> value, Widget child) =>
                      value.length > 0 && value.contains("Record Payment")
                          ? FormStatusWidget(
                              enable: Container(),
                              disable: Center(
                                child: NormalBorderButton(
                                  title: S.current.record_payment,
                                  onTap: provider.onRecordPayment,
                                  isFit: true,
                                ),
                              ),
                            )
                          : Container(),
            ),
            AppSpaces.h30,
            listBuilder<List<String>>(
              selector: (_, __) => List.from(__.menuList),
              builder:
                  (BuildContext context, List<String> value, Widget child) =>
                      value.length > 0 && value.contains("See Payment")
                          ? FormStatusWidget(
                              enable: Container(),
                              disable: Center(
                                child: NormalBorderButton(
                                  title: S.current.see_payment,
                                  onTap: provider.onSeePayment,
                                  isFit: true,
                                ),
                              ),
                            )
                          : Container(),
            ),
            AppSpaces.h30,
          ],
        ),
      );
}
